package com.example.coreshopapp;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.coreshopapp.app.Constants;
import com.example.coreshopapp.base.BaseActivity;
import com.example.coreshopapp.bean.DangbanData;
import com.example.coreshopapp.bean.DangbanReq;
import com.example.coreshopapp.bean.MemberData;
import com.example.coreshopapp.bean.SystemSnData;
import com.example.coreshopapp.bean.SystemSnReq;
import com.example.coreshopapp.bean.SysuserData;
import com.example.coreshopapp.databinding.ActivityMainBinding;
import com.example.coreshopapp.net.BaseApplication;
import com.example.coreshopapp.task.ContinueClassBillNoTask;
import com.example.coreshopapp.task.DangbanTask;
import com.example.coreshopapp.task.JiaobanTask;
import com.example.coreshopapp.task.SystemTask;
import com.example.coreshopapp.ui.BillPayActivity;
import com.example.coreshopapp.ui.ClassBillActivity;
import com.example.coreshopapp.ui.ClassifyActivity;
import com.example.coreshopapp.ui.LoginActivity;
import com.example.coreshopapp.ui.MemberActivity;
import com.example.coreshopapp.ui.OrderDetailActivity;
import com.example.coreshopapp.ui.OrderFormActivity;
import com.example.coreshopapp.utils.DeviceInfo;
import com.example.coreshopapp.utils.LoadingUtils;
import com.google.gson.Gson;

import java.util.HashMap;

import dao.DaoSession;
import dao.OrderBeanDao;
import dao.OrderItemBeanDao;

public class MainActivity extends BaseActivity {
    private ActivityMainBinding binding;
    private DangbanReq dangbanReq = new DangbanReq();
    private Context context;
    //    private Button confirm;
    private AlertDialog dialog;

    @SuppressLint("HandlerLeak")
    private Handler snHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) { // 处理传递回来数据
            LoadingUtils.hideProgressDialog();
//            confirm.setEnabled(true); // 关闭按钮控制
            switch (msg.what) {
                case 9900:
                    // 存储当班信息
                    SystemSnData systemData = JSON.parseObject( msg.obj.toString(),SystemSnData.class);
                    Constants.AppConstVars.SnInfo = systemData;
                    getDangbanInfo();
                    settingSystem();
                    break;
                case 9901:
                case 9902:
                    goLogin(LoginActivity.class);
                    Toast.makeText(MainActivity.this, "获取设备号失败，请退出登录重新获取", Toast.LENGTH_LONG).show();
                    break;
                 case 9904:
                  goLogin(LoginActivity.class);
                    Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
            }
            super.handleMessage(msg);
        }
    };
    @SuppressLint("HandlerLeak")
    private Handler dangbanHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) { // 处理传递回来数据
            LoadingUtils.hideProgressDialog();
//            confirm.setEnabled(true); // 关闭按钮控制
            switch (msg.what) {
                case 9900:
                    // 存储当班信息
                    if(msg.obj == null) {
                        Constants.AppConstVars.classBillNo = "";
                            dangbanClick();
                    } else {
                        // ncStatus 1 交班中退出登录等待， 3 交班失败 弹出弹窗，看看需不需要
                        DangbanData dangbanData =  JSON.parseObject(msg.obj.toString(),DangbanData.class);
                        switch(dangbanData.getNcStatus()) {
                            case 1:
                                goLogin(LoginActivity.class);
                                showtoast(MainActivity.this,"交班中，请稍后重试");
                                break;
                            case 3 :
                                new AlertDialog.Builder(MainActivity.this)
                                        .setTitle("温馨提示")
                                        .setMessage("交班失败，是否继续使用上一个当班信息")
                                        .setPositiveButton("确定", (dialogInterface, i) -> {
                                            LoadingUtils.showProgressDialog(getActivity(), "温馨提示", "加载中，请稍后");
                                            HashMap<String, String> obj = new HashMap<>();
                                            obj.put("classBillNo",dangbanData.getClassBillNo());
                                            ContinueClassBillNoTask continueClassBillNoTask = new ContinueClassBillNoTask(obj);
                                            continueClassBillNoTask.setOutHandler(contiuneHandler);
                                            continueClassBillNoTask.execute();
                                            Constants.AppConstVars.classBillNo = dangbanData.getClassBillNo();
                                        })
                                        .setNegativeButton("切换新的当班人", (dialogInterface, i) -> {
                                            Constants.AppConstVars.classBillNo = "";
                                            dangbanClick();
                                        })
                                        .show();
                                break;
                            default:
                        Constants.AppConstVars.classBillNo = dangbanData.getClassBillNo();
                                break;
                        }
                    }
                    settingSystem();
                    break;
                case 9901:
                    goLogin(LoginActivity.class);
                    Toast.makeText(MainActivity.this, "请求失败：" + msg.obj, Toast.LENGTH_LONG).show();
                    break;
                case 9902:
//                    goLogin(LoginActivity.class);
//                    Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
//                    break;
                case 9904:
                    goLogin(LoginActivity.class);
                    Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
            }
            super.handleMessage(msg);
        }
    };
    @SuppressLint("HandlerLeak")
    private Handler contiuneHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) { // 处理传递回来数据
            LoadingUtils.hideProgressDialog();
//            confirm.setEnabled(true); // 关闭按钮控制
            switch (msg.what) {
                case 9900:
                    break;
                case 9901:
                    goLogin(MainActivity.class);
                    showtoast(MainActivity.this, "请求失败：" + msg.obj);
                    break;
                case 9902:
                    Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
                case 9904:
                    goLogin(LoginActivity.class);
                    Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
            }
            super.handleMessage(msg);
        }
    };
  @SuppressLint("HandlerLeak")
    private Handler jiaobanHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) { // 处理传递回来数据
            LoadingUtils.hideProgressDialog();
//            confirm.setEnabled(true); // 关闭按钮控制
            switch (msg.what) {
                case 9900:
                    // 交班后将信息删除
                   goLogin(LoginActivity.class);
                    // 交班成功，删除交班信息还有本地信息还有退出登录，以及token之类信息
                    DaoSession daoSession = BaseApplication.getInstance().getDaoSession(MainActivity.this);
                    OrderBeanDao orderBeanDao = daoSession.getOrderBeanDao();
                    OrderItemBeanDao orderItemBeanDao = daoSession.getOrderItemBeanDao();
                    orderBeanDao.deleteAll();
                    orderItemBeanDao.deleteAll();
                    break;
                case 9901:
                    Toast.makeText(MainActivity.this, "请求失败：" + msg.obj, Toast.LENGTH_LONG).show();
                    break;
                case 9902:
                    Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
                case 9904:
                    goLogin(LoginActivity.class);
                    Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        hideTopBar();
        getStorage();
        initView();
        getDao();
        viewClick();
        getQuery();
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        settingSystem();
    }

    private void settingSystem() {
        MemberData memberInfo = Constants.AppConstVars.MemberInfo;
        String classBillNo = Constants.AppConstVars.classBillNo;
        SystemSnData snInfo = Constants.AppConstVars.SnInfo;
        SysuserData sysUser = Constants.AppConstVars.sysUser;
        binding.tvClassBillNo.setText(classBillNo!=null && !classBillNo.equals("") ? classBillNo :"");
        binding.tvNickname.setText(sysUser!=null?sysUser.getNickName():"");
        binding.tvPos.setText(snInfo !=null? snInfo.getFItemID()+"":"");
        binding.tvStoreName.setText(sysUser!=null?sysUser.getStoreName():"");
        binding.tvMember.setText(memberInfo!=null ? memberInfo.getNickName():"未登录会员");
    }

    private void getQuery() {
        Bundle extras = getIntent().getExtras();
        if(extras !=null ) {
            String dangban = extras.getString("dangban");
            if(dangban != null & dangban.equals("dangban")){
                dangbanClick();
            }
        }
    }

    private void getDao() {
        if (Constants.AppConstVars.SnInfo == null) {
            LoadingUtils.showProgressDialog(this, "温馨提示", "加载中，请稍后");
            String deviceSerial = DeviceInfo.getDeviceSerial(MainActivity.this);
            SystemSnReq systemSnReq = new SystemSnReq(deviceSerial, Constants.AppConstVars.sysUser.getStoreId());
            SystemTask systemTask = new SystemTask(systemSnReq);
            systemTask.setOutHandler(snHandler);
            systemTask.execute();
        }

    }

    private void getStorage() {
//        dangbanInfo = getSharedPreferences("dangbanInfo", MODE_PRIVATE);
//        Constants.AppConstVars.classBillNo = dangbanInfo.getString("classBillNo","");
    }

    private void viewClick() {
        binding.dangban.setOnClickListener(view -> {
            // 收银当班
            dangbanClick();
        });
        binding.goods.setOnClickListener(view -> {
            gotoActivity(ClassifyActivity.class);
        });
        binding.ordering.setOnClickListener(view -> {
            gotoActivity(OrderFormActivity.class);
        });
        // 交班
        binding.jiaoban.setOnClickListener(view -> {
            if (Constants.AppConstVars.classBillNo.equals("")) {
                showtoast(this, "当前未有当班人");
                return;
            }
            new AlertDialog.Builder(this).setTitle("温馨提示").setMessage("确认交班吗")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确定", (dialogInterface, i) -> {
                        HashMap<Object, Object> obj = new HashMap<>();
                        obj.put("data",Constants.AppConstVars.classBillNo);
                        obj.put("pushToNc",0);
                        Gson gson = new Gson();
                        Log.d( "viewClick: ",JSON.toJSONString(obj) + Constants.AppConstVars.classBillNo);
                        JiaobanTask jiaobanTask = new JiaobanTask(gson.toJson(obj));
                        jiaobanTask.setOutHandler(jiaobanHandler);
                        jiaobanTask.execute();
                        LoadingUtils.showProgressDialog(MainActivity.this,"温馨提示","交班中，请稍后");
                    }).create().show();
        });
//        binding.logoutLogin.setOnClickListener(view -> {
//            new AlertDialog.Builder(this).setTitle("温馨提示").setMessage("确认退出登录吗")
//                    .setNegativeButton("取消", null)
//                    .setPositiveButton("确定", (dialogInterface, i) -> {
//                        goLogin(LoginActivity.class);
//                    }).create().show();
//        });
        binding.checkUser.setOnClickListener(view -> {
            gotoActivity(MemberActivity.class);
        });
        binding.tvClassBill.setOnClickListener(view -> {
          gotoActivity(ClassBillActivity.class);
        });
        binding.billPay.setOnClickListener(view -> {
            gotoActivity(BillPayActivity.class);
        });
    }

    private void initView() {
        context = getActivity();
    }


    public void dangbanClick() {
//        int sysuserId = dangbanInfo.getInt("sysuserId",0);
        if (!Constants.AppConstVars.classBillNo.equals("")) {
            showtoast(this, "已有当班人，请先交班");
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.AlertDialogCustom);
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_shouyindangban, null, false);

        TextView cashboxmoney = dialogView.findViewById(R.id.class_money_tv);
        Button num1 = dialogView.findViewById(R.id.num1);
        Button num2 = dialogView.findViewById(R.id.num2);
        Button num3 = dialogView.findViewById(R.id.num3);
        Button num4 = dialogView.findViewById(R.id.num4);
        Button num5 = dialogView.findViewById(R.id.num5);
        Button num6 = dialogView.findViewById(R.id.num6);
        Button num7 = dialogView.findViewById(R.id.num7);
        Button num8 = dialogView.findViewById(R.id.num8);
        Button num9 = dialogView.findViewById(R.id.num9);
        Button num0 = dialogView.findViewById(R.id.num0);
        Button num00 = dialogView.findViewById(R.id.num00);
        Button numdian = dialogView.findViewById(R.id.numdian);
        Button numx = dialogView.findViewById(R.id.numx);
        Button numjian = dialogView.findViewById(R.id.numjian);
        ImageView dialog3_close = dialogView.findViewById(R.id.close);
        Button confirm = dialogView.findViewById(R.id.confirm);


        num1.setOnClickListener(v -> {
            String temp = cashboxmoney.getText().toString();
            if (temp.length() <= 12) {
                if (temp.length() >= 4) {
                    String ss = temp.substring(temp.length() - 3, temp.length() - 2);
                    if (!ss.equals(".")) {
                        cashboxmoney.setText(temp + "1");
                    } else {
                        String text = context.getResources().getString(R.string.main_meal_twodecimal);
                        showtoast(MainActivity.this, text);
                    }
                } else {
                    cashboxmoney.setText(temp + "1");
                }
            }

        });
        num2.setOnClickListener(v -> {
            String temp = cashboxmoney.getText().toString();
            if (temp.length() <= 12) {
                if (temp.length() >= 4) {
                    String ss = temp.substring(temp.length() - 3, temp.length() - 2);
                    if (!ss.equals(".")) {
                        cashboxmoney.setText(temp + "2");
                    } else {
                        String text = context.getResources().getString(R.string.main_meal_twodecimal);
                        showtoast(MainActivity.this, text);
                    }
                } else {
                    cashboxmoney.setText(temp + "2");
                }
            }
        });
        num3.setOnClickListener(v -> {
            String temp = cashboxmoney.getText().toString();
            if (temp.length() <= 12) {
                if (temp.length() >= 4) {
                    String ss = temp.substring(temp.length() - 3, temp.length() - 2);
                    if (!ss.equals(".")) {
                        cashboxmoney.setText(temp + "3");
                    } else {
                        String text = context.getResources().getString(R.string.main_meal_twodecimal);
                        showtoast(MainActivity.this, text);
                    }
                } else {
                    cashboxmoney.setText(temp + "3");
                }
            }
        });
        num4.setOnClickListener(v -> {
            String temp = cashboxmoney.getText().toString();
            if (temp.length() <= 12) {
                if (temp.length() >= 4) {
                    String ss = temp.substring(temp.length() - 3, temp.length() - 2);
                    if (!ss.equals(".")) {
                        cashboxmoney.setText(temp + "4");
                    } else {
                        String text = context.getResources().getString(R.string.main_meal_twodecimal);
                        showtoast(MainActivity.this, text);
                    }
                } else {
                    cashboxmoney.setText(temp + "4");
                }
            }
        });
        num5.setOnClickListener(v -> {
            String temp = cashboxmoney.getText().toString();
            if (temp.length() <= 12) {
                if (temp.length() >= 4) {
                    String ss = temp.substring(temp.length() - 3, temp.length() - 2);
                    if (!ss.equals(".")) {
                        cashboxmoney.setText(temp + "5");
                    } else {
                        String text = context.getResources().getString(R.string.main_meal_twodecimal);
                        showtoast(MainActivity.this, text);
                    }
                } else {
                    cashboxmoney.setText(temp + "5");
                }
            }
        });
        num6.setOnClickListener(v -> {
            String temp = cashboxmoney.getText().toString();
            if (temp.length() <= 12) {
                if (temp.length() >= 4) {
                    String ss = temp.substring(temp.length() - 3, temp.length() - 2);
                    if (!ss.equals(".")) {
                        cashboxmoney.setText(temp + "6");
                    } else {
                        String text = context.getResources().getString(R.string.main_meal_twodecimal);
                        showtoast(MainActivity.this, text);
                    }
                } else {
                    cashboxmoney.setText(temp + "6");
                }
            }
        });
        num7.setOnClickListener(v -> {
            String temp = cashboxmoney.getText().toString();
            if (temp.length() <= 12) {
                if (temp.length() >= 4) {
                    String ss = temp.substring(temp.length() - 3, temp.length() - 2);
                    if (!ss.equals(".")) {
                        cashboxmoney.setText(temp + "7");
                    } else {
                        String text = context.getResources().getString(R.string.main_meal_twodecimal);
                        showtoast(MainActivity.this, text);
                    }
                } else {
                    cashboxmoney.setText(temp + "7");
                }
            }
        });
        num8.setOnClickListener(v -> {
            String temp = cashboxmoney.getText().toString();
            if (temp.length() <= 12) {
                if (temp.length() >= 4) {
                    String ss = temp.substring(temp.length() - 3, temp.length() - 2);
                    if (!ss.equals(".")) {
                        cashboxmoney.setText(temp + "8");
                    } else {
                        String text = context.getResources().getString(R.string.main_meal_twodecimal);
                        showtoast(MainActivity.this, text);
                    }
                } else {
                    cashboxmoney.setText(temp + "8");
                }
            }
        });
        num9.setOnClickListener(v -> {
            String temp = cashboxmoney.getText().toString();
            if (temp.length() <= 12) {
                if (temp.length() >= 4) {
                    String ss = temp.substring(temp.length() - 3, temp.length() - 2);
                    if (!ss.equals(".")) {
                        cashboxmoney.setText(temp + "9");
                    } else {
                        String text = context.getResources().getString(R.string.main_meal_twodecimal);
                        showtoast(MainActivity.this, text);
                    }
                } else {
                    cashboxmoney.setText(temp + "9");
                }
            }
        });
        num0.setOnClickListener(v -> {
            String temp = cashboxmoney.getText().toString();
            if (temp.length() == 0) {
                cashboxmoney.setText("0.");
            } else if (temp.length() == 1) {
                if (temp.equals("0")) {
                    //..
                } else {
                    cashboxmoney.setText(temp + "0");
                }
            } else {
                if (temp.length() <= 12) {
                    if (temp.length() >= 4) {
                        String ss = temp.substring(temp.length() - 3, temp.length() - 2);
                        if (!ss.equals(".")) {
                            cashboxmoney.setText(temp + "0");
                        } else {
                            String text = context.getResources().getString(R.string.main_meal_twodecimal);
                            showtoast(MainActivity.this, text);
                        }
                    } else {
                        cashboxmoney.setText(temp + "0");
                    }
                }
            }

        });
        num00.setOnClickListener(v -> {
            String temp = cashboxmoney.getText().toString();
            if (temp.length() == 0) {
                cashboxmoney.setText("0.");
            } else if (temp.length() == 1) {
                if (temp.equals("0")) {
                    //..
                } else if (temp.equals("-")) {
                    cashboxmoney.setText(temp + "0");
                } else {
                    cashboxmoney.setText(temp + "00");
                }
            } else if (temp.length() == 2) {
                if (temp.equals("-0")) {
                    //..
                } else {
                    cashboxmoney.setText(temp + "00");
                }
            } else {
                if (temp.length() <= 12) {
                    if (temp.length() == 3) {
                        String ss = temp.substring(temp.length() - 2, temp.length() - 2);
                        if (!ss.equals(".")) {
                            cashboxmoney.setText(temp + "0");
                        } else {
                            String text = context.getResources().getString(R.string.main_meal_twodecimal);
                            showtoast(MainActivity.this, text);
                        }
                    } else if (temp.length() > 3) {
                        String ss = temp.substring(temp.length() - 3, temp.length() - 2);
                        if (!ss.equals(".")) {
                            cashboxmoney.setText(temp + "0");
                        } else {
                            String text = context.getResources().getString(R.string.main_meal_twodecimal);
                            showtoast(MainActivity.this, text);
                        }
                    } else {
                        cashboxmoney.setText(temp + "00");
                    }
                }
            }

        });
        numdian.setOnClickListener(v -> {
            String temp = cashboxmoney.getText().toString();
            if (temp.length() == 0) {
                cashboxmoney.setText("0.");
            } else if (temp.length() == 1) {
                if (temp.equals("-")) {
                    cashboxmoney.setText("-0.");
                } else {
                    cashboxmoney.setText(temp + ".");
                }
            } else {
                boolean iscontain = temp.contains(".");
                if (!iscontain) {
                    if (temp.length() <= 12) {
                        cashboxmoney.setText(temp + ".");
                    }
                }
            }
        });
        numx.setOnClickListener(v -> {
            String temp = cashboxmoney.getText().toString();
            if (temp.length() > 0 && temp.length() == 1) {
                cashboxmoney.setText("");
            }
            if (temp.length() > 1) {
                String s = temp.substring(0, temp.length() - 1);
                cashboxmoney.setText(s);
            }
        });
        numjian.setOnClickListener(v -> {
            String temp = cashboxmoney.getText().toString();
            if (temp.contains("-")) {
                String s = temp.replaceAll("-", "");
                cashboxmoney.setText(s);
            } else {
                cashboxmoney.setText("-" + temp);
            }
        });
        builder.setView(dialogView);
        dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);//点空白不消失

        confirm.setOnClickListener(v -> {
            String temp = cashboxmoney.getText().toString();
//            dangbanReq = new DangbanReq(
//                    TimeUtils.getNo(Constants.AppConstVars.sysUser.getStoreId()),
//                    "", temp,
//                    Constants.AppConstVars.sysUser.getId(),
//                    "",
//                    Constants.AppConstVars.SnInfo.getFItemID()
//            );
            dangbanReq = new DangbanReq(
                    Constants.AppConstVars.SnInfo.getFItemID(),
                    Constants.AppConstVars.sysUser.getId()
            );
            DangbanTask dangbanTask = new DangbanTask(dangbanReq);
            dangbanTask.setOutHandler(dangbanHandler);
            dangbanTask.execute();
            dialog.dismiss();
            LoadingUtils.showProgressDialog(getActivity(), "温馨提示", "加载中，请稍后");
            confirm.setEnabled(false); // 关闭按钮控制

        });

        dialog3_close.setOnClickListener(v -> dialog.dismiss());
        dialog.show();
    }

    public void getDangbanInfo() {
        DangbanReq dangbanReq = new DangbanReq(
                Constants.AppConstVars.SnInfo.getFItemID(),
                Constants.AppConstVars.sysUser.getId()
        );
        DangbanTask dangbanTask = new DangbanTask(dangbanReq);
        dangbanTask.setOutHandler(dangbanHandler);
        dangbanTask.dangbanInfoExecute();
        LoadingUtils.showProgressDialog(getActivity(), "温馨提示", "加载中，请稍后");
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}